<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Dept;
use Symfony\Component\HttpKernel\Exception\HttpException;

class DeptController extends Controller
{
    // 初始化保存模型
    protected function initialize()
    {
        $this->model = new Dept();
    }

    public function index()
    {
        $list = $this->model::orderBy('sort')->get();
        return $this->success(message: '获取成功', data: $list->toArray());
    }

    public function store(Request $request)
    {
        $body = $request->json()->all();

        try {
            $dept = $this->model::create($body);
            return $this->success(data: ['id' => $dept->id]);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function update($id, Request $request)
    {
        $body = $request->json()->all();
        try {
            $this->model::where('id', $id)->update($body);
            return $this->success(message: '修改成功');
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function destroy($id)
    {
        try {
            $this->model::destroy($id);
            return $this->success(message: '删除成功');
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }
}
